package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.cp.api.entity.sync.SyncFundStdDataInfoHisEntity;
import com.pactera.madp.cp.api.vo.prod.ProdFundNavTendencyVo;
import com.pactera.madp.cp.mapper.sync.SyncFundStdDataInfoHisMapper;
import com.pactera.madp.cp.service.sync.SyncFundStdDataInfoHisService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SyncFundStdDataInfoHisServiceImpl extends ServiceImpl<SyncFundStdDataInfoHisMapper, SyncFundStdDataInfoHisEntity> implements SyncFundStdDataInfoHisService {

    @Override
    public void syncOneDay(String syncDate) {
        // 插入历史表前，删除可能存在的上一天数据
        this.remove(Wrappers.<SyncFundStdDataInfoHisEntity>lambdaQuery()
                .eq(SyncFundStdDataInfoHisEntity::getSyncDate, syncDate));
        // 同步上一天数据到历史表
        baseMapper.syncData(syncDate);
    }

    @Override
    public void deleteOneDate(String date) {
        this.remove(Wrappers.<SyncFundStdDataInfoHisEntity>lambdaQuery()
                .le(SyncFundStdDataInfoHisEntity::getSyncDate, date));
    }

    @Override
    public List<ProdFundNavTendencyVo> fundNavTendency(String code) {
        String before30 = DateUtil.formatDate(DateUtil.offsetDay(DateUtil.date(), -30));
        List<SyncFundStdDataInfoHisEntity> entities = this.baseMapper.selectList(
                Wrappers.<SyncFundStdDataInfoHisEntity>lambdaQuery()
                        .select(SyncFundStdDataInfoHisEntity::getIssDate, SyncFundStdDataInfoHisEntity::getNav)
                .eq(SyncFundStdDataInfoHisEntity::getPrdCode, code)
                .eq(SyncFundStdDataInfoHisEntity::getDelFlag, 0)
                .gt(SyncFundStdDataInfoHisEntity::getIssDate, before30)
        ).stream().distinct().collect(Collectors.toList());
        List<ProdFundNavTendencyVo> vos = new ArrayList<>();
        entities.sort(Comparator.comparing(s -> s.getIssDate()));
        entities.forEach(s -> {
            String date = DateUtil.formatDate(DateUtil.parse(s.getIssDate(), "yyyyMMdd"));
            ProdFundNavTendencyVo vo = new ProdFundNavTendencyVo();
            vo.setNavDate(date);
            BigDecimal bd = new BigDecimal(s.getNav());
            vo.setNav(bd.stripTrailingZeros().toPlainString());
            vos.add(vo);
        });
        return vos;
    }

}